package org.jash.shop2112.pay

import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alipay.sdk.app.PayTask
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import org.jash.shop2112.R
import org.jash.shop2112.databinding.ActivityPayBinding
import org.jash.shop2112.mvvm.BaseActivity
import org.jash.shop2112.mvvm.BaseViewModel
import org.jash.shop2112.utils.alipay.OrderInfoUtil2_0.buildOrderParam
import org.jash.shop2112.utils.alipay.OrderInfoUtil2_0.buildOrderParamMap
import org.jash.shop2112.utils.alipay.OrderInfoUtil2_0.getSign
import org.jash.shop2112.utils.alipay.PayResult
import org.jash.shop2112.utils.log
import java.util.concurrent.Executors


@Route(path = "/shop/pay")
class PayActivity : BaseActivity<ActivityPayBinding, BaseViewModel>() {
    @Autowired
    @JvmField
    var info:String = ""
    @Autowired
    @JvmField
    var price:Float = 0f

    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    val APPID = "9021000136678494"

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    val PID = "2088721035210245"

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    val TARGET_ID = "sandbox 默认应用:2088721035210245"

    /**
     * pkcs8 格式的商户私钥。
     *
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     *
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    val RSA2_PRIVATE =
        "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDD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yO+uOxRgw9rzh/koH3eb9LytGgVdeQI9KAl5sGwBSqY4cwdq6uDeCoU/jRqO3UDuEbrSGTP0FCJkG1TjsaY+06FpNBLsHpGlCjtoBQdrHo6ri4qIlxbN4niKqvyCPwKBgC2aYAdREPkNNghkPhZmkRu7UbpUXZm8p6mhu+LxySTxrzEc6sGMFuQ8jftccuy8bf0nclT4JbQsZJbA5FLuGrB5tgwEgZfRb4BfW7VdCJ0H17a4eX1a0ju6EQndfxuI+ZnnopSJBRz8CBIjAfSzUdMVR1lZZ0xksDwR6MDh9TcRAoGBAIRQxq5Ku82DbsIYG69kfwxrg2uOAv/4bJ3efAR9D/EcUK3NWs6P54tR0oT/Xia/a+2yKATBGFxHXJc3LZ/4gHnysDEEI04ptCmfdCo7ieR1XQ7O5dSH5ux16FiZi9f/FDgOb+oloIQATWujIBzLhD0Zc2vspQHv0dgYSraaLaI7"
    val RSA_PRIVATE = ""

    val executor = Executors.newSingleThreadExecutor()
    val liveData = MutableLiveData<PayResult>()
    lateinit var mLocationClient:LocationClient
    override fun initData() {
        liveData.observe(this) {
            when(it.resultStatus) {
                "9000" -> Toast.makeText(this, "支付功成", Toast.LENGTH_SHORT).show()
                else -> Toast.makeText(this, "支付失败, 原因:${it.memo}", Toast.LENGTH_SHORT).show()
            }
        }
        try {
            LocationClient.setAgreePrivacy(true)
            mLocationClient = LocationClient(getApplicationContext())
            val option =  LocationClientOption();

            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);


            option.setCoorType("bd09ll");


            option.setFirstLocType(LocationClientOption.FirstLocType.SPEED_IN_FIRST_LOC)


            option.setScanSpan(1000);


            option.setOpenGnss(true);


            option.setLocationNotify(true);

            option.setIgnoreKillProcess(false);

            option.SetIgnoreCacheException(false);

            option.setWifiCacheTimeOut(5*60*1000);

            option.setEnableSimulateGnss(false);


            option.setNeedNewVersionRgc(true);


            mLocationClient.setLocOption(option);

            mLocationClient.start()
            mLocationClient.unRegisterLocationListener(object :BDAbstractLocationListener() {
                override fun onReceiveLocation(location: BDLocation?) {
                    log("${location?.city}: ${location?.latitude}-${location?.longitude}")
                }

            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient.stop()
    }
    override fun initView() {
        ARouter.getInstance().inject(this)
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        binding.info.setText(info)
        binding.price.setText(resources.getString(R.string.price_format, price))
        binding.pay.setOnClickListener {
            val rsa2 = RSA2_PRIVATE.length > 0
            val params: Map<String, String?> = buildOrderParamMap(APPID, rsa2, price, info)
            val orderParam = buildOrderParam(params)

            val privateKey = if (rsa2) RSA2_PRIVATE else RSA_PRIVATE
            val sign = getSign(params, privateKey, rsa2)
            val orderInfo = "$orderParam&$sign"

            executor.execute {
                val alipay = PayTask(this)
                val result = alipay.payV2(orderInfo, true)
                liveData.postValue(PayResult(result))
            }
        }
    }
}